package com.stx.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.stx.common.PageValue;
import com.stx.common.PlayerSessionUtil;
import com.stx.common.Result;
import com.stx.pojo.Player;
import com.stx.pojo.Record;
import com.stx.pojo.Ruanyue;
import com.stx.pojo.vo.DashboardVO;
import com.stx.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.Session;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@CrossOrigin
@RestController
@Tag(name = "评分记录相关接口")
@RequestMapping("/record")
public class RecordController {

    @Autowired
    private RecordService recordService;
    @Autowired
    private MatchService matchService;
    @Autowired
    private JudgeService judgeService;
    @Autowired
    private RuanyueService ruanyueService;

    @Autowired
    private PlayerService playerService;
    @Autowired
    private IRecordService jrecordService;

    private static final Logger logger = LogManager.getLogger(RecordController.class);

    private ObjectMapper objectMapper = new ObjectMapper();

    @Operation(
            summary = "列表",
            description = "评分记录列表",
            tags = {"评分记录相关接口"}
    )
    @GetMapping("/list")
    public Result getplayer() {
        List<Record> list = jrecordService.list();
        return Result.success(list);
    }

    @Operation(
            summary = "评分通道接口",
            description = "评分通道接口",
            tags = {"评分记录相关接口"}
    )
    @PostMapping("/score")
    public Result score(@RequestBody Record record, HttpServletRequest request) {
        try {
            // 先判断评分通道是否打开;
            Session session = PlayerSessionUtil.getPlayerSession(record.getPlaId());
            if (Objects.isNull(session)) {
                logger.info("评分通道未打开");
                return Result.error("当前选手的评分通道尚未开启");
            } else {
                logger.info("评分通道打开");
                Integer userId = (Integer) request.getAttribute("userId");
                record.setJudId(userId);
                Player player = playerService.getById(record.getPlaId());
                record.setPlaName(Objects.isNull(player) ? "" : player.getPlaName());
                String judName = (String) request.getAttribute("nickName");
                record.setJudName(judName);
                //获取当前时间
                record.setRecDate(LocalDateTime.now());
                //根据软约id来查找软约的期数,需要前端把软约id传回来
                Ruanyue ruanyue = ruanyueService.getById(record.getRuaId());
                record.setRuaNumber(Objects.isNull(ruanyue) ? null : ruanyue.getRuaNumber());
                recordService.save(record);
                // 计算平均分
                logger.info(record + "dhjfdk");
                Ruanyue action = ruanyueService.last();
                List<Record> list = recordService.findByPlayerId(record.getPlaId(), action.getId());//增加期数
                BigDecimal averageScore = new BigDecimal(recordService.calculateAverageScore(list)).setScale(2, BigDecimal.ROUND_HALF_UP);
                System.out.println(averageScore);
                DashboardVO vo = new DashboardVO();
                vo.setAvgScore(averageScore);
                System.out.println(record.getJudId());
                vo.setJudeId(record.getJudId());
                System.out.println(record.getJudId());
                vo.setJudeScore(record.getRecScore());
                System.out.println(record.getRecScore());
                // 将平均分推送给所有连接的客户端
                session.getAsyncRemote().sendText(objectMapper.writeValueAsString(vo));
                logger.info("将平均分推送给所有连接的客户端");
                return Result.success();
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("评分通道未打开");
            return Result.error("评分通道未打开");
        }
    }

    /*@PostMapping("/save")
    public Result save(@RequestBody Record record) {
        Double recScore = record.getRecScore();
        System.out.println(recScore);
        if (record.getId() == null) {
            recordService.add(record);
        } else {
            recordService.update(record);
        }
        return Result.success();
    }*/
//
//    @DeleteMapping("/{id}")
//    public Result delete(@PathVariable Integer id) {
//        //recordService.delete(id);
//        jrecordService.removeById(id);
//        return Result.success();
//    }

    @Operation(
            summary = "根据打分员id查询打分记录",
            description = "根据打分员id查询打分记录",
            tags = {"评分记录相关接口"}
    )
    @PostMapping("/listByJudger")
    public Result listByJudger(HttpServletRequest request) {
        Integer userId = (Integer) request.getAttribute("userId");
        List<Record> records = recordService.listByJudger(userId);
        return Result.success(records);
    }

    @Operation(
            summary = "分页查询打分记录",
            description = "分页查询打分记录",
            tags = {"评分记录相关接口"}
    )
    @PostMapping("/page")
    public Result findPage(@Validated @RequestBody PageValue pageValue) {
        if (pageValue.getCurrentPage() != null && pageValue.getPageSize() != null) {
            Page<Record> page = recordService.find(pageValue.getPlaName(), pageValue.getJudRole(), pageValue.getNumber(), pageValue.getCurrentPage(), pageValue.getPageSize());
            return Result.success(page);
        } else {
            List<Record> list = jrecordService.list();
            return Result.success(list);
        }
    }
    @Operation(
            summary = "方法二计算平均分",
            description = "不去掉最值计算平均分",
            tags = {"评分记录相关接口"}
    )
    @PostMapping("reset")
    public Result resetSocre(@RequestBody Record record){
        LambdaQueryWrapper<Record> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Record::getRuaNumber,record.getRuaNumber());
        wrapper.eq(Record::getPlaId,record.getPlaId());
        List<Record> list = jrecordService.list(wrapper);
        // 创建一个ArrayList来临时存储分数，方便后续操作
        List<Double> scoresList = new ArrayList<>();
        for (Record r : list) {
            scoresList.add(r.getRecScore());
        }
        System.out.println(scoresList);
        // 计算分数总和
        double sum = 0;
        for (Double score : scoresList) {
            sum += score;
        }
        System.out.println("avg"+sum);
        // 计算平均分，防止除数为0的情况，若没有获取到任何分数，返回0.0
        BigDecimal averageScore = new BigDecimal(scoresList.size() > 0? sum / scoresList.size() : 0.0).setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal reset = averageScore;
        return Result.success(reset);
    }
}
